using System;
using System.Collections.Generic;
using System.Threading;
using LockerRack.Drawers;
using LockerRack.Helpers;
using LockerRack.Interfaces;
using Primitive.Mvvm.Framework.Implementations;
using Primitive.Mvvm.Framework.Interfaces;
using UIController.Models;

namespace UIController.ViewModels
{
    internal class ThreadExecutiveViewModel : BaseViewModel
    {
        private ToDoModel _model;
        private ManualResetEventSlim _stopEvent;
        private TimeSpan _defaultTimeSpan = new TimeSpan(0, 30, 0);
        private IList<IDrawerFile> _reminders;

        public TimeSpan DefaultTimeSpan
        {
            get { return _defaultTimeSpan; }
            set { _defaultTimeSpan = value; }
        }

        
        public IList<IDrawerFile> Reminders
        {
            get
            {
                return _reminders;
            }
            set
            {
                _reminders = value;
                RaisePropertyChanged(this, () => Reminders);
            }
        }

        public ThreadExecutiveViewModel(IModel model, IMediator mediator, ManualResetEventSlim stopEvent) : base(mediator)
        {
            _model = model as ToDoModel;
            _stopEvent = stopEvent;
            _reminders = new List<IDrawerFile>();
        }

        public void DoWork()
        {
            if (_model == null || _stopEvent == null)
                return;

            for(;!_stopEvent.Wait(_defaultTimeSpan);)
            {
                //do work
                var files = GetAllDrawerFilesRecurcively(_model.Drawers);
                var reminders = new List<IDrawerFile>();
                foreach (var drawerFile in files)
                {
                    var bag = drawerFile.Contents.With(c => c.PropertyBag);
                    if(PropertyExists(bag, "IssueDate"))
                    {
                        DateTime issueDate = bag.IssueDate;
                        if(DateTime.Now < issueDate)
                            continue;

                        reminders.Add(drawerFile);
                    }
                }

                Reminders = reminders;
            }
        }

        private IEnumerable<IDrawerFile> GetAllDrawerFilesRecurcively(IList<Drawer> drawers)
        {
            var list = new List<IDrawerFile>();
            foreach (var drawer in drawers)
            {
                var files = GetAllDrawerFilesRecurcively(drawer.Drawers);
                list.AddRange(files);
                list.AddRange(drawer.Files);
            }

            return list;
        }
    }
}